﻿package com.francois
{
	import com.francois.constant.KeyCode;
	
	import flash.debugger.enterDebugger;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public class HelloWorld extends MovieClip
	{
		private var car:CarSpirit;
		
		private var inputs : Array = new Array();
		
		private var keyDownArray : Array = new Array();
		
		public function HelloWorld()
		{
			car = new CarSpirit();
		}
		
		/**
		 * All start here 
		 * 
		 */
		public function start() : void	
		{
			trace("ALL START");
			init();
		}
		
		public function init() : void
		{
			initCar();
			this.stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownEventHandler);
			this.stage.addEventListener(KeyboardEvent.KEY_UP,keyUpEventHandler);
			this.stage.frameRate = 33;
			this.stage.addEventListener(Event.ENTER_FRAME,updateHandler);
		}
		
		public function updateHandler(event:Event) : void
		{
			handleKeyCode();
		}
		
		
		public function keyDownEventHandler(event:KeyboardEvent) : void
		{
			inputs.push(event.keyCode);
			if(!arrayContains(keyDownArray,event.keyCode))
			{
				keyDownArray.push(event.keyCode);
			}
		}

		public function arrayContains(array:Array,value:int) : Boolean
		{
			for(var i:int=0;i<array.length;i++)
			{
				if(array[i] == value)
				{
					return true;
				}
			}
			return false;
		}
			
		public function keyUpEventHandler(event:KeyboardEvent) : void
		{
			keyDownArray = keyDownArray.filter(filterNull);
			for(var i:int = 0;i<keyDownArray.length;i++)
			{
				if(keyDownArray[i] == event.keyCode)
				{
					keyDownArray[i] = -1;
				}
			}
		}
		
		private function filterNull(element:*, index:int, arr:Array) : Boolean
		{
			if(element == -1)
			{
				return false;
			}
			return true;
		}

		private function handleKeyCode() : void
		{
			while(inputs.length>0)
			{
				//trace(inputs.length);
				handleKeyCodeLogic(inputs.pop());
			}
			
			trace("keyDown Length");
			trace(keyDownArray.length);
			for(var i:int=0;i<keyDownArray.length;i++)
			{
				handleKeyCodeLogic(keyDownArray[i]);
			}
		}
		
		public function handleKeyCodeLogic(keyCode:int) : void
		{
			switch(keyCode)
			{
				case KeyCode.UP:
				{
					car.y -= 1;
					break;
				}
				case KeyCode.DOWN:
				{
					car.y += 1;
					break;
				}
				case KeyCode.LEFT:
				{
					car.x -= 1;
					break;
				}
				case KeyCode.RIGHT:
				{
					car.x += 1;
					break;
				}
			}
		}
		
		public function initCar() : void 
		{
			car.x = 50;
			car.y = 100;
			this.addChild(car);
		}
	}
}